<template>
  <div class="pageList-detail">
    <page-list :pageOption="pageOption" :btnIsDisabled="btnIsDisabled" ref="tableRef">
      <template #bodyCell="{ column, text, record, index }">
        <a-input-number :controls="false" :disabled="column.isDisabled" v-if="column.editComponent == 'Custom_InputNumber'" v-model:value="record[column['dataIndex']]" @change="scoreCompute" @focus="handleIndex(index)" />
      </template>
      <template #tipsBefore>
        <a-button type="primary" class="btn" @click="handleInit()" :disabled="btnIsDisabled">初始化</a-button>
      </template>
      <template #tips>
        <page-list :pageOption="detailPageOption" ref="detailTableRef" class="detailTable">
          <template #tips> 综合评价明细 </template>
        </page-list>
      </template>
    </page-list>
  </div>
</template>

<script lang="ts" name="emp-team-checkIn3-HubTeamResultEvaluate" setup>
import { ref,provide, onMounted, reactive, nextTick, watchEffect, computed, unref, watch, defineComponent } from 'vue';

import PageList from '../../../components/newPageList/index.vue';
import { unifyNumber } from '/@/views/zhc/util/numUtils';
import { getPluraList, getPeriodTree, getMonitoringStatus } from '/@/api/common/api';
import { getColumn, getTemplateConfigHeader, deleteOne, init } from './HubTeamResultEvaluate.api';
import dayjs from 'dayjs';
import { useMessage } from '/@/hooks/web/useMessage';
import { render } from '/@/utils/common/renderUtils';
import { renderDict } from '../../../components/utils/index';
import { cloneDeep } from 'lodash-es';
import { useUrlSearchParams } from '@vueuse/core';
const btnIsDisabled = ref(false);
// 轻提醒
const { createMessage: $message } = useMessage();
const tableRef = ref(null);
const detailTableRef = ref(null);
const pageParams = {
  orgCodeBase: '',
  orgNameBase: '',
  periodCode: '',
};
let dynamicHeader = [];
let currentTableIndex = 0; //记录当前操作的表格数据行
const pageOption = {
  dataUrl: '/emp/hubTeamResultEvaluate',
  method: 'GET',
  showCreate: false,
  batchEdit: true,
  showTableSetting: false,
  immediate: false,
  saveParams: { orgCode: pageParams.orgCodeBase },
  beforeFetch: (params) => {
    let periodCode = tableRef.value.getForm().getFieldsValue()?.periodCode?.slice(0, 4);
    getDynamicData({ orgCode: pageParams.orgCodeBase, type: '1', periodCode });
    // getTableColumn({ orgCode: pageParams.orgCodeBase, type: '1' });
    detailTableRef.value.reload();
    return Object.assign(params);
  },
  afterFetch: (tableData) => {
    let columns = tableRef.value.getColumns();
    columns.forEach((item) => {
      if (item.children) {
        item.children.forEach((child) => {
          if (child.defaultWeight) {
            tableData.list?.forEach((data) => {
              data[child.dataIndex] = child.defaultWeight;
            });
          }
        });
      }
    });
    return tableData;
  },
  // beforeSave: () => {
  //   let tableData = tableRef.value.getTableData();
  //   let flag = true;
  //   dynamicHeader.forEach((i) => {
  //     if (i.children?.length > 0) {
  //       i.children.forEach((child) => {
  //         if (child.headName == '评分') {
  //           tableData.forEach((data) => {
  //             if (!data[child.headCode] && data[child.headCode] !== 0) {
  //               flag = false;
  //             }
  //           });
  //         }
  //       });
  //     }
  //   });
  //   if (!flag) {
  //     $message.error('评分项不能为空');
  //   }
  //   return flag;
  // },
  searchForm: [
    {
      field: 'periodCode',
      label: '考核周期',
      component: 'ApiTreeSelect',
      componentProps: {
        api: getPeriodTree,
        // options: [],
        fieldNames: {
          children: 'child',
          label: 'periodName',
          value: 'periodCode',
        },
        onChange: (e) => {
          pageParams.periodCode = e;
          getBtnStatus(pageParams);
        },
      },
      colProps: { span: 8 },
      defaultValue: dayjs().format('YYYYMM'),
    },
    {
      field: 'orgCode',
      component: 'Select',
      label: '班组',
      componentProps: {
        options: [],
        immediate: true,
      },
      colProps: {
        span: 8,
      },
    },
    {
      field: 'psnName',
      label: '员工姓名',
      component: 'Input',
      colProps: { span: 8 },
    },
  ],
  columns: [
    {
      title: '主键',
      align: 'center',
      dataIndex: 'id',
      ifShow: false,
    },
    {
      title: '班组编码',
      align: 'center',
      dataIndex: 'orgCode',
      ifShow: false,
    },
    {
      title: '班组名称',
      align: 'center',
      dataIndex: 'orgName',
      width: 160,
    },
    {
      title: '人员类型',
      align: 'center',
      dataIndex: 'personType',
      width: 160,
      customRender: ({ text }) => {
        return renderDict(text, ['hub_person_type1', 'hub_person_type2']);
      },
    },
    {
      title: '考核周期',
      align: 'center',
      dataIndex: 'periodCode',
      width: 160,
      // customRender: ({ text }) => {
      //   return text.slice(0, 4) + '年' + text.slice(4) + '月';
      // },
    },
    {
      title: '员工姓名',
      align: 'center',
      dataIndex: 'psnName',
      width: 160,
    },
    {
      title: '综合得分',
      align: 'center',
      dataIndex: 'finalScore',
      width: 160,
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'status',
      width: 160,
      ifShow: false,
    },
  ],
  customActions: [
    {
      label: '删除',
      action: 'customDelete',
      confirm: '确认删除吗',
      dynamicRules: () => {
        return btnIsDisabled.value;
      },
    },
  ],
};
const detailPageOption = {
  dataUrl: '/emp/hubTeamEvaluateIndex',
  method: 'GET',
  title: '综合评价明细',
  showCreate: false,
  batchEdit: false,
  showSearchForm: false,
  showActionColumn: false,
  useBatchDelete: false,
  noSelection: true,
  showTableSetting: false,
  pagination: false,
  immediate: false,
  beforeFetch: (params) => {
    let periodCode = tableRef.value.getForm().getFieldsValue()?.periodCode?.slice(0, 4);
    getTableColumn({ orgCode: pageParams.orgCodeBase, type: '1' });
    return Object.assign(params, { orgCode: pageParams.orgCodeBase, type: '1', periodCode: periodCode });
  },
  columns: [
    {
      title: '主键',
      align: 'center',
      dataIndex: 'id',
      ifShow: false,
    },
    {
      title: '指标',
      align: 'center',
      dataIndex: 'indexName',
      width: 160,
    },
    {
      title: '权重（%）',
      align: 'center',
      dataIndex: 'factorWeight',
      width: 160,
    },
  ],
};

//自定义删除方法
const customDelete = async (record) => {
  // tableRef.value?.handleDelete(record);
  await deleteOne({ id: record.id });
  tableRef.value?.reload();
};

provide('customDelete', customDelete);
/**
 * 动态表头配置
 * @param params
 */
const getDynamicData = (params) => {
  let newColumn = cloneDeep(pageOption.columns);
  getColumn(params).then((res) => {
    dynamicHeader = res;
    res.forEach((r) => {
      let temp = {
        title: r.headName,
      };
      //多级表头处理
      let childList = r.children;
      if (childList) {
        //有子列表情况
        let newChildList = [];
        childList.forEach((r1) => {
          let childTemp = {
            title: r1.headName,
            dataIndex: r1.headCode,
            width: 260,
            align: 'center',
            editComponent: 'Input',
          };
          // if (r1.headName == '评分') {
          //   childTemp.required = true;
          // }
          if (r1.headName == '评分' || r1.headName == '权重') {
            childTemp.editComponent = 'Custom_InputNumber';
            childTemp.width = 120;
          }
          if (r1.headName == '权重') {
            childTemp.title = '权重（%）';
            childTemp.isDisabled = true;
          }
          if (r1.headCode.indexOf('weight') != -1) {
            childTemp.defaultWeight = r.value;
          }
          newChildList.splice(newChildList.length, 0, { ...childTemp });
        });
        temp['children'] = newChildList;
      }

      newColumn.splice(newColumn.length - 2, 0, {
        ...temp,
        checkDetail: r.checkDetail, //判断是否能打开详情 boolean
        scopedSlots: { customRender: r.headCode },
      });
    });
    // newColumn[newColumn.length - 1]['fixed'] = 'right';
    //重设表头
    nextTick(() => {
      tableRef.value?.setColumns(newColumn);
    });
  });
};

// 获取详情动态表头
const getTableColumn = async (params) => {
  let newColumn = cloneDeep(detailPageOption.columns);
  getTemplateConfigHeader(params).then((res) => {
    res.forEach((item) => {
      let temp = {
        title: item.headName,
        dataIndex: item.headCode,
        width: 180,
        align: 'center',
      };
      newColumn.splice(newColumn.length, 0, {
        ...temp,
      });
    });
    nextTick(() => {
      detailTableRef.value?.setColumns(newColumn);
    });
  });
};

// 初始化
const handleInit = () => {
  let formData = tableRef.value?.getForm().getFieldsValue();
  // tableRef.value.reload();
  init({
    orgCode: pageParams.orgCodeBase,
    periodCode: formData.periodCode,
  }).then((res) => {
    tableRef.value.reload();
  });
};

// 计算分数
const scoreCompute = () => {
  console.log('1111111111');
  let TableData = tableRef.value?.getTableData();
  let column = tableRef.value?.getColumns();
  let currentRecord = TableData[currentTableIndex];
  currentRecord.finalScore = 0;
  // 规定10
  for (let i = 1; i <= 10; i++) {
    if (currentRecord[`score${i}`] && currentRecord[`weight${i}`]) {
      console.log('计算currentRecord', currentRecord);
      currentRecord.finalScore += (currentRecord[`score${i}`] / 100) * currentRecord[`weight${i}`];
    }
  }
  currentRecord.finalScore = unifyNumber(currentRecord.finalScore);
};

const handleIndex = (index) => {
  currentTableIndex = index;
};

const getBtnStatus = (pageParams) => {
  getMonitoringStatus({
    orgCode: pageParams.orgCodeBase,
    periodCode: pageParams.periodCode,
  }).then((res) => {
    if (res.data == '2') {
      btnIsDisabled.value = true;
    } else {
      btnIsDisabled.value = false;
    }
  });
};

nextTick(() => {
  let form = tableRef.value.getForm();
  let periodCode = form.getFieldsValue()?.periodCode;
  getPluraList().then((res) => {
    pageParams.orgCodeBase = res[0]?.orgCode;
    pageParams.orgNameBase = res[0]?.orgName;
    pageParams.periodCode = periodCode;
    if (!pageParams.orgCodeBase) return;
    getBtnStatus(pageParams);
    tableRef.value.getForm().updateSchema({
      field: 'orgCode',
      component: 'Select',
      label: '班组',
      componentProps: {
        options: res,
        immediate: true,
        onChange: (e) => {
          pageParams.orgCodeBase = e;
          getBtnStatus(pageParams);
          tableRef.value.reload();
          detailTableRef.value.reload();
        },
      },
      colProps: {
        span: 8,
      },
      defaultValue: res[0]?.orgCode,
    });
    tableRef.value.getForm().setFieldsValue({
      orgCode: res[0]?.orgCode,
    });
    tableRef.value.reload();
    detailTableRef.value.reload();
  });
});
</script>
<style lang="less" scoped>
.pageList-detail {
  /deep/ .items-center {
    display: block !important;
  }

  /deep/.zenith-basic-table-header__toolbar {
    height: 34px;
  }

  .btn {
    margin-right: 8px;
  }
}
</style>
